package com.atguigu.edu.config;

import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 获取applicationContext 方便获取bean
 * 用于无法注入的容器组件使用容器中的bean
 *
 * @author zy
 */
public class BeanContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @SneakyThrows
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanContextUtils.applicationContext = applicationContext;

    }

    /**
     * 通过静态方法返回
     *
     * @return
     */
    public static ApplicationContext getBeanFactory() {
        return BeanContextUtils.applicationContext;
    }

    /**
     * getBean方法
     *
     * @param beanName
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        T bean = BeanContextUtils.applicationContext.getBean(beanName, clazz);
        return bean;
    }

}
